package ru.ng.sample.core.notes;

import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * User: NGorosh
 * Date: 20.05.11
 * Time: 14:18
 */
@Repository
public class NoteManager
{
    private static final List<Note> notes = new ArrayList<Note>();
    private static int idGenerator = 1;

    static
    {
        notes.add( new Note( idGenerator++ , "What's New in Spring 3.0", "New Features and Enhancements in Spring 3.0" ) );
        notes.add( new Note( idGenerator++ , "Core Technologies",
                             "The IoC container, Resources, Validation, Data Binding, and Type Conversion" ) );
    }

    public List<Note> getNotes()
    {
        return notes;
    }

    public Note getNote(int id)
    {
        for (Note n : notes)
        {
            if (n.getId() == id)
                return n;
        }
        return null;
    }

    public Note add(Note note)
    {
        if (note == null)
            throw new NullPointerException( "note is null!!!" );

        Note n = new Note( );
        n.setId( idGenerator++ );
        n.setName( note.getName() );
        n.setText( note.getText() );
        notes.add( n );
        return n;
    }

    public Note edit(Note note)
    {
        if (note == null)
            throw new NullPointerException( "note is null!!!" );
        if (note.getId() == null)
            throw new NullPointerException( "note id cannot be null" );

        Note n = getNote(note.getId());

        if (n == null)
            throw new IllegalStateException( String.format("Note %s is not exist ", note) );

        n.setName( note.getName() );
        n.setText( note.getText() );
        return n;
    }

    public void delete(int noteId)
    {
        Note n = getNote(noteId);
        notes.remove( n );
    }
}
